package utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

/**
 * token 工具类
 */
public class TokenUtil {
    //token到期时间10小时
    private static final long EXPIRE_TIME = 10 * 60 * 60 * 1000;
    //密钥盐
    private static final String TOKEN_SECRET = "shzu_bcxy_20191008197";

    /**
     * 生成token,并将其存入redis缓存中
     *
     * @param username TODO:最好改成用户ID
     * @return 返回生成的token
     */
    public static String sign(String username) {

        String token = null;
        try {
            //获取当前时间，生成过期时间
            Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0") //发行人
                    .withClaim("username", username) //存放数据
                    .withExpiresAt(expireAt) //过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException je) {
            je.printStackTrace();
        }
        return token;
    }


    /**
     * token验证
     *
     * @param token
     * @return 返回token验证结果 true：验证通过，false：验证失败
     */
    public static Boolean verify(String token) {

        try {
            //创建token验证器
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            System.out.println("认证通过：");    //TODO 需要删除
            System.out.println("username: " + decodedJWT.getClaim("username").asString());
            System.out.println("过期时间：      " + decodedJWT.getExpiresAt());  //TODO 需要删除
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            return false;
        }
        return true;
    }
}